import React, { useRef, useState } from 'react';
import { PageContainer, ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Drawer, Form, Input, message, Popconfirm } from 'antd';
import { useRequest } from 'umi';
import { fetchCartList, createCartItem, updateCartItem, deleteCartItem } from '@/services/ant-design-pro/product'; // 假设你已经定义了这些服务

const CartList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.CartItem | undefined>();
  const [isEditMode, setIsEditMode] = useState<boolean>(false);
  const [form] = Form.useForm();

  const { run: createRun } = useRequest(createCartItem, {
    manual: true,
    onSuccess: () => {
      message.success('创建成功');
      setDrawerVisible(false);
      actionRef.current?.reload();
    },
    onError: () => {
      message.error('创建失败');
    },
  });

  const { run: updateRun } = useRequest(updateCartItem, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功');
      setDrawerVisible(false);
      actionRef.current?.reload();
    },
    onError: () => {
      message.error('更新失败');
    },
  });

  const { run: deleteRun } = useRequest(deleteCartItem, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      actionRef.current?.reload();
    },
    onError: () => {
      message.error('删除失败');
    },
  });

  const handleSave = async (values: API.CartItem) => {
    if (isEditMode && currentRow) {
      await updateRun({ ...currentRow, ...values });
    } else {
      await createRun(values);
    }
  };

  const columns: ProColumns<API.CartItem>[] = [
    {
      title: '费用',
      dataIndex: 'amount',
    },
    {
      title: '调用量',
      dataIndex: 'callCount',
    },
    {
      title: '调用方式',
      dataIndex: 'callWay',
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
    },
    {
      title: '生效时间',
      dataIndex: 'effectTime',
      valueType: 'dateTime',
    },
    {
      title: '服务城市',
      dataIndex: 'serviceCity',
    },
    {
      title: '服务时长',
      dataIndex: 'serviceTime',
    },
    {
      title: '服务类别',
      dataIndex: 'serviceType',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRow(record);
            setIsEditMode(true);
            form.setFieldsValue(record);
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除该购物车项吗？"
          onConfirm={() => deleteRun(record.id)}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.CartItem, API.PageParams>
        headerTitle="购物车列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              setCurrentRow(undefined);
              setIsEditMode(false);
              form.resetFields();
              setDrawerVisible(true);
            }}
          >
            新建购物车项
          </Button>,
        ]}
        request={fetchCartList}
        columns={columns}
      />

      <Drawer
        title={isEditMode ? '编辑购物车项' : '新建购物车项'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        closable={false}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={currentRow}
        >
          <Form.Item
            name="amount"
            label="费用"
            rules={[{ required: true, message: '请输入费用' }]}
          >
            <Input type="number" placeholder="请输入费用" />
          </Form.Item>
          <Form.Item
            name="callCount"
            label="调用量"
            rules={[{ required: true, message: '请输入调用量' }]}
          >
            <Input placeholder="请输入调用量" />
          </Form.Item>
          <Form.Item
            name="callWay"
            label="调用方式"
            rules={[{ required: true, message: '请输入调用方式' }]}
          >
            <Input placeholder="请输入调用方式" />
          </Form.Item>
          <Form.Item
            name="dataType"
            label="数据类型"
            rules={[{ required: true, message: '请输入数据类型' }]}
          >
            <Input placeholder="请输入数据类型" />
          </Form.Item>
          <Form.Item
            name="effectTime"
            label="生效时间"
            rules={[{ required: true, message: '请输入生效时间' }]}
          >
            <Input type="datetime-local" placeholder="请输入生效时间" />
          </Form.Item>
          <Form.Item
            name="serviceCity"
            label="服务城市"
            rules={[{ required: true, message: '请输入服务城市' }]}
          >
            <Input placeholder="请输入服务城市" />
          </Form.Item>
          <Form.Item
            name="serviceTime"
            label="服务时长"
            rules={[{ required: true, message: '请输入服务时长' }]}
          >
            <Input placeholder="请输入服务时长" />
          </Form.Item>
          <Form.Item
            name="serviceType"
            label="服务类别"
            rules={[{ required: true, message: '请输入服务类别' }]}
          >
            <Input placeholder="请输入服务类别" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              {isEditMode ? '更新' : '创建'}
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => setDrawerVisible(false)}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default CartList;